<script lang="ts" setup>
import type { EvaluationType, HomeworkCardType, PhaseType } from '@/types/micro-scene';
import SubTitle from './components/SubTitle.vue';
import fronticon from "@/assets/front/front1.png";
import { computed, onMounted, ref } from 'vue';
import { useUserStore } from '@/stores/useUserStore';
import { CheckOutlined, CloseOutlined, DeleteOutlined, EditOutlined, LinkOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons-vue';
import HomeworkModal from './components/HomeworkModal.vue';
import { Modal, message } from 'ant-design-vue';
import { addPhaseHomework, addPhaseSubmittedHomeworkApi, deletePhaseHomework, deletePhaseSubmittedHomeworkApi, getPhaseInfo, getPhaseSubmittedHomeworkListApi, updatePhaseHomework } from '@/api/MicroScene/MicroSceneDetailApi';
import { useRoute } from 'vue-router';
import { validateNull } from '@/utils/validate';

const props = defineProps<{
  phaseId: string
  beginEndId: string
}>()
const route = useRoute()
const userStore = useUserStore()
const homeworkRequirement = ref<string>('');
const evaluation = ref<EvaluationType>({
  totalScore: 0,
  gainedScore: 0,
  homeworkComment: '',
});

// 添加删除模块的状态
const isModuleVisible = ref(true);

const getText = async () => {
  const response = await getPhaseInfo(route.params.id as string, props.phaseId)
  homeworkRequirement.value = response.workRequirement;
  evaluation.value.totalScore = response.workScore;
  isModuleVisible.value = response.workExist;
}

const isEdit = ref(false);
const evaluationCache = ref<EvaluationType>();
const showEdit = computed(() => {
  return userStore.isEditMicroScene
})
const handleEdit = () => {
  isEdit.value = true;
  evaluationCache.value = evaluation.value;
}
const handleCancel = () => {
  isEdit.value = false;
  evaluation.value = evaluationCache.value as EvaluationType;
}
const handleSave = async () => {
  isEdit.value = false;

  try {
    await updatePhaseHomework(Number(route.params.id), Number(props.phaseId), homeworkRequirement.value, evaluation.value.totalScore)
  }
  catch (error) {
    console.error('更新阶段作业失败', error)
    message.error('更新阶段作业失败')
  }
  finally {
    // 保存后，清零其余
    evaluation.value.gainedScore = 0;
    evaluation.value.homeworkComment = '';
  }
}

const showHomeworkModal = ref(false);

const handleShowHomeworkModal = (showModal: boolean) => {
  showHomeworkModal.value = showModal;
}

// 已提交的作品列表
const submittedHomeworkList = ref<HomeworkCardType[]>([]);

// 获取以及提交作品列表
const getSubmittedHomeworkList = async () => {
  try {
    const response = await getPhaseSubmittedHomeworkListApi(props.beginEndId, props.phaseId)
    if (validateNull(response.phaseOpusId)) {
      submittedHomeworkList.value = []
      evaluation.value.gainedScore = 0;
      evaluation.value.homeworkComment = '';
    }
    else {
      // 作品只有一个，因此直接赋值即可
      submittedHomeworkList.value = [{
        opusId: response.phaseOpusId,
        opusTitle: response.opusTitle,
        introduction: response.introduction,
        score: response.score,
        remark: response.remark,
        commitTime: response.commitTime,
      }]
      evaluation.value.gainedScore = response.score;
      evaluation.value.homeworkComment = response.remark;
    }
  }
  catch (error) {
    console.error('获取已提交作品列表失败', error)
    message.error('获取已提交作品列表失败')
  }
}

const handleDeleteHomework = async () => {
  // 删除作品
  submittedHomeworkList.value = [];
  try {
    await deletePhaseSubmittedHomeworkApi(props.beginEndId, props.phaseId)
  }
  catch (error) {
    console.error('删除作品失败', error)
    message.error('删除作品失败')
  }
}

// 删除模块的处理函数
const handleDeleteModule = async () => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除阶段作品模块吗',
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk() {
      isModuleVisible.value = false;
      message.success('已删除阶段作品模块');
    },
  });
  await deletePhaseHomework(Number(route.params.id), Number(props.phaseId))
  // 保存后，清零其余
  evaluation.value.gainedScore = 0;
  evaluation.value.homeworkComment = '';
  submittedHomeworkList.value = [];
};

// 添加模块的按钮
const handleAddModule = async () => {
  await addPhaseHomework(Number(route.params.id), Number(props.phaseId))
  const response = await getPhaseInfo(route.params.id as string, props.phaseId)
  homeworkRequirement.value = response.workRequirement;
  evaluation.value.totalScore = response.workScore;
  isModuleVisible.value = true;
}

// 上传作业
const handleUploadHomework = async (formData: HomeworkCardType, imgFileList: any[], homeworkFileList: any[]) => {
  try {
    // 上传作业,文件列表里面只用第一个文件
    await addPhaseSubmittedHomeworkApi(props.beginEndId, props.phaseId, formData.introduction || '', formData.homeworkLabel || [], formData.opusTitle || '', imgFileList[0].originFileObj, homeworkFileList[0].originFileObj)
    message.success('上传作业成功')
    getSubmittedHomeworkList()
  }
  catch (error) {
    console.error('上传作业失败', error)
    message.error('上传作业失败')
  }
}

onMounted(() => {
  getText();
  getSubmittedHomeworkList();
})
</script>

<template>
  <div v-if="isModuleVisible">
    <div class="flex flex-row">
      <SubTitle title="阶段作品" />
      <div v-if="showEdit" class="flex items-center ml-4">
        <!-- 标题编辑区域 -->
        <a-button type="text" @click="handleEdit">
          <template #icon>
            <EditOutlined />
          </template>
        </a-button>
        <a-button type="text" danger @click="handleDeleteModule">
          <template #icon>
            <DeleteOutlined />
          </template>
        </a-button>
        <a-button v-show="isEdit" @click="handleCancel">
          <template #icon>
            <CloseOutlined />
          </template>
        </a-button>
        <a-button v-show="isEdit" type="primary" @click="handleSave">
          <template #icon>
            <CheckOutlined />
          </template>
        </a-button>
      </div>
    </div>
    <div class="flex gap-4 my-6">
      <div class="">
        <img :src="fronticon" alt="fronticon" class="w-4 h-4">
      </div>
      <div class="flex-1 space-y-2">
        <div class="font-bold">
          作品要求
        </div>
        <div v-show="!isEdit" class="text-[0.875rem] leading-6 whitespace-pre-wrap">
          {{ homeworkRequirement }}
        </div>
        <a-textarea
          v-show="isEdit" v-model:value="homeworkRequirement" :auto-size="{ minRows: 3, maxRows: 10 }"
          class="w-full"
        />
      </div>
    </div>
    <!-- 提交作品部分 -->
    <div class="my-2 gap-2">
      <a-button type="primary" @click="handleShowHomeworkModal(true)">
        提交作品
        <template #icon>
          <UploadOutlined />
        </template>
      </a-button>
      <!-- 已经提交的作品列表 -->
      <a-list :data-source="submittedHomeworkList">
        <template #renderItem="{ item }">
          <a-list-item class="text-blue-500 select-none">
            <div class="flex items-center justify-between">
              <LinkOutlined />
              <span class="text-blue-500 ml-2">
                {{ `${item.opusTitle} ${item.commitTime}` }}
              </span>
              <a-button
                type="primary" danger size="small" class="text-xs ml-4"
                @click="handleDeleteHomework()"
              >
                <template #icon>
                  <DeleteOutlined class="text-xs" />
                </template>
              </a-button>
            </div>
          </a-list-item>
        </template>
      </a-list>
    </div>
    <HomeworkModal :show-modal="showHomeworkModal" @update:show-modal="handleShowHomeworkModal" @upload-homework="handleUploadHomework" />
    <div class="flex gap-4 my-6">
      <div class="">
        <img :src="fronticon" alt="fronticon" class="w-4 h-4">
      </div>
      <div class="flex-1 space-y-2">
        <div class="font-bold">
          作品评价
        </div>
        <div v-show="!isEdit" class="text-[0.875rem] leading-6">
          本次作品总分：{{ evaluation.totalScore }} 分
        </div>
        <div v-show="!isEdit" class="text-[0.875rem] leading-6">
          已获得 {{ evaluation.gainedScore }} 分
        </div>
        <div v-show="!isEdit" class="text-[0.875rem] leading-6 whitespace-pre-wrap">
          {{ evaluation.homeworkComment }}
        </div>
        <!-- 编辑模式 -->
        <div v-show="isEdit" class="flex items-center my-4">
          <span class="text-[0.875rem]">该阶段总分数：</span>
          <a-input v-model:value="evaluation.totalScore" class="w-32" placeholder="请输入总分" />
          <span class="text-[0.875rem] ml-2">分(所有阶段分数和不能大于100分)</span>
        </div>
      </div>
    </div>
  </div>
  <div v-else>
    <div class="flex items-center justify-center h-full">
      <a-button type="primary" @click="handleAddModule">
        添加阶段作品模块
        <template #icon>
          <PlusOutlined />
        </template>
      </a-button>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
